package org.teremail.message;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.teremail.util.IO;

public class MemoryContentStore implements ContentStore {

    private volatile long currentId = 1;
    private final Map<String,byte[]> data = new ConcurrentHashMap<String,byte[]>();
    
    public Content create(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IO.copy(in, out);
        String id = String.valueOf(++currentId);
        data.put(id, out.toByteArray());
        return new Content(id);
    }

    public InputStream getInputStream(Content c) {
        if (data.containsKey(c.getId())) {
            return new ByteArrayInputStream(data.get(c.getId()));
        } else {
            throw new RuntimeException("Id not found: " + c.getId());
        }
    }

    public Content create(String text, Charset encoding) throws IOException {
        return create(new ByteArrayInputStream(text.getBytes(encoding)));
    }

}
